package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleClient;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Service
public class AuditServiceImpl implements IAuditService {
    @Autowired
    GreenImageScan imageScan;
    @Autowired
    GreenTextScan textScan;
    @Autowired
    IWmNewsService wmNewsService;

    @Autowired
    private RedissonClient redissonClient;
    @Override
    @Async
    public void audit(WmNews wmNews) {
        System.out.println(Thread.currentThread().getName() + "开始审核");
        if (wmNews.getStatus() == 8 || wmNews.getStatus() == 4){
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                saveArticle(wmNews);
            }else {
//                发布延时任务
                long time = wmNews.getPublishTime().getTime();
                long time1 = time - System.currentTimeMillis();
                RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("article.ftl");
                RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
                delayedQueue.offer(wmNews.getId().toString(),time, TimeUnit.MILLISECONDS);

            }

            return;
        }
//        状态是否为1
        if (wmNews.getStatus() == 1) {
//            获取文本很普片
            Map<String, Object> map = createTextAndImage(wmNews);
//            获取文本
            String text = (String) map.get("text");
//            获取图片
            List<String> image = (List<String>) map.get("image");
//            自定义审核
            Boolean reultSelf = selfText(wmNews, text);
            if (!reultSelf) return;
//            审核文本
            Boolean reluet = createText(wmNews, text);
            if (!reluet) return;
//           将封面图片加入集合中进行审核
            List<ImageDto> imageDtos = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            for (ImageDto imageDto : imageDtos) {
                image.add(imageDto.getUrl());
            }
//            审核图片
            Boolean resultImage = createImage(wmNews, image);
            if (!resultImage) return;

//             添加文章
            saveArticle(wmNews);
            System.out.println(Thread.currentThread().getName() + "审核结束");

        }

    }
    @Autowired
    private IWmSensitiveService wmSensitiveService;
    /**
     * 自定义审核
     * @param wmNews
     * @param text
     * @return
     */
    private Boolean selfText(WmNews wmNews, String text) {
//        判断是不是第一次审核
        if (SensitiveWordUtil.dictionaryMap.size() == 0){
//            是 初始化数据
//            1.查询数据
            LambdaQueryWrapper<WmSensitive> query = new LambdaQueryWrapper<>();
            query.select(WmSensitive::getSensitives);
            List<String> list = wmSensitiveService.listObjs(query, o -> o.toString());
            SensitiveWordUtil.initMap(list);

        }
//        否 数据匹配
        text = wmNews.getTitle() + wmNews.getLabels() + text;
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(text);
        if (stringIntegerMap.size() > 0){
//            修改状态
            wmNews.setStatus(2);
            Set<String> strings = stringIntegerMap.keySet();
            String join = String.join(",", strings);
            wmNews.setReason(join);
            wmNewsService.updateById(wmNews);
            System.out.println("失败原因是："+join);
            return false;
        }
//        审核成功继续阿里云审核
        return true;
    }

    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private ArticleClient articleClient;

    /**
     * 保存文章
     *
     * @param wmNews
     */
    private void saveArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        dto.setTitle(wmNews.getTitle());
//        从wmUser中条件数据
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        dto.setAuthorId(wmUser.getApAuthorId());
        dto.setAuthorName(wmUser.getName());
//       从频道中获取数据
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        dto.setChannelId(wmChannel.getId());
        dto.setChannelName(wmChannel.getName());
        dto.setLayout(wmNews.getType());
//      将封面图片转换加入，
        String images = wmNews.getImages();
        List<ImageDto> imageDtos = JSON.parseArray(images, ImageDto.class);
        List<String> list = new ArrayList<>();
        for (ImageDto imageDto : imageDtos) {
            list.add(imageDto.getUrl());
        }
//        加入逗号分离
        String join = String.join(",", list);
        dto.setImages(join);
        dto.setContent(wmNews.getContent());
        ResponseResult<Long> longResponseResult = articleClient.saveArticle(dto);
        if (longResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            Long data = longResponseResult.getData();
            if (data != null) {
//                将文章id协会到自媒体表中
                wmNews.setArticleId(data);
//                将状态修改为9
                wmNews.setStatus(9);
                wmNewsService.updateById(wmNews);
            }
        }

    }


    @Autowired
    private MinIOService minIOService;

    /**
     * 审核图片
     *
     * @param wmNews
     * @param images
     * @return
     */
    private Boolean createImage(WmNews wmNews, List<String> images) {
        Boolean flag = false;
//        判断image是否为空
        if (images.size() == 0) {
            flag = true;
        }
        try {
//        创建数组
            List<byte[]> imageList = new ArrayList<>();
//        遍历image
            for (String image : images) {
                //            判断image是否为空
                if (!StringUtils.isEmpty(image)) {
                    //                在minio下载图片
                    InputStream download = minIOService.download(image);
                    byte[] bytes = IOUtils.toByteArray(download);
                    imageList.add(bytes);
                }
            }
//        审核图片
            Map map = imageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
//            判断是 通过 失败 不确定
            switch (suggestion) {
                case "pass":
                    flag = true;
                    break;
                case "block":
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason(label);
                    wmNewsService.updateById(wmNews);
                    break;
                case "review":
                    wmNews.setStatus(3);
                    wmNewsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 审核文本
     *
     * @param wmNews
     * @param text
     * @return
     */
    private Boolean createText(WmNews wmNews, String text) {
        Boolean flag = false;
//        审核内容 = 标题+标签+文本
        text = wmNews.getTitle() + wmNews.getLabels() + text;

        try {
//        调用阿里云的方法
            Map map = textScan.greenTextScan(text);
//            获取返回信息
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    flag = true;
                    break;
                case "block":
//                    修改状态 ，提交失败原因
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("审核失败烟瘾是：" + label);
                    wmNewsService.updateById(wmNews);
                    break;
                case "review":
                    wmNews.setStatus(3);
                    wmNewsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 获取文章的 文本 和 图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> createTextAndImage(WmNews wmNews) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        List<String> image = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                sb.append(contentDto.getValue());
            }
            if (contentDto.getType().equals("image")) {
                image.add(contentDto.getValue());
            }
        }
        map.put("text", sb.toString());
        map.put("image", image);
        return map;
    }


}
